import { cityApi } from "@/utils/api";

// 城市模块
const cityModule = {
  // 让getters,mutations,actions都放在模块下
  namespaced: true,
  state: {
    // 城市改变
    cityName: localStorage.getItem("cityName") || "北京",
    cityId: localStorage.getItem("cityId") || 110100,

    // 城市列表
    cityList: [],
  },
  getters: {
    hotCity(state) {
      return state.cityList[0];
    },
    otherCity(state) {
      return state.cityList.slice(1);
    },
  },
  mutations: {
    changeCity(state, payload) {
      state.cityName = payload.name;
      state.cityId = payload.cityId;
      localStorage.setItem("cityName", payload.name);
      localStorage.setItem("cityId", payload.cityId);
    },
    getCityList(state, payload) {
      state.cityList = payload.result;
    },
  },
  actions: {
    async getCityListAsync({ commit }) {
      const res = await cityApi();
      commit("getCityList", res);
    },
  },
};

export default cityModule;
